<template>
  <div class="product-section">
    <el-row>
      <el-col :span="24">
        <h3 class="section-title">{{ title }}</h3>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="product-row">
      <!-- 商品列表 -->
      <el-col
          :span="productSpan"
          v-for="(product, index) in products"
          :key="index"
          class="product-col"
      >
        <el-card
            :body-style="{ padding: '0px' }"
            @click.native="onCardClick(product)"
            class="product-card"
        >
          <img :src="product.img" class="product-img"/>
          <div class="product-info">
            <div class="product-title">{{ product.title }}</div>
            <div class="product-desc">{{ product.desc }}</div>
            <div class="product-price">¥{{ product.price }}</div>
            <el-button type="text" class="buy-btn"
            >立即购买 <i class="el-icon-arrow-right"></i
            ></el-button>
          </div>
        </el-card>
      </el-col>

      <!-- 动态生成的空块用于补齐 -->
      <el-col
          v-for="index in emptyCols"
          :key="'empty-' + index"
          :span="productSpan"
          class="product-col empty-col"
      >
        <div class="empty-block"></div>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="24">
        <el-pagination
            background
            layout="prev, pager, next"
            :page-size="pageSize"
            :current-page="currentPage"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :total="total"
        >
        </el-pagination>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import router from "@/router";
import {mapMutations} from "vuex";
import {productsPageQuery} from "@/api/productsApi";

export default {
  name: "ProductListComponent",
  props: {
    title: String,
    productSpan: {
      type: Number,
      default: 6, // 默认每行显示4个商品
    },
    productType: {
      type: Number,
      default: 1, //商品查询类别
    },
  },
  data() {
    return {
      total: 0,
      currentPage: 1,
      pageSize: 12,
      categoryId: "",
      /**
       * query 主要用于加载商品列表
       */
      query: {
        productId: "",
        productName: "",
        storeId: "",
        categoryId: "",
      },
      type: 0,
      products: [

      ],
      currentProductType: 0,
    };
  },
  computed: {
    // 计算需要补齐的空块数量
    emptyCols() {
      const totalCols = 24 / this.productSpan; // 每行总列数
      const neededCols = totalCols - (this.products.length % totalCols);
      // const neededCols = 0;
      return neededCols === totalCols ? 0 : neededCols;
    },
  },
  watch: {
    /**
     * 监听路由中商品类别的变化
     * @param newType
     * @param oldType
     */
    "$route.params.productType"(newType, oldType) {
      if (newType !== oldType) {
        this.currentProductType = newType;
        this.loadGoodsPageQuery(); // 加载对应的商品数据
      }
    },
  },
  created() {
    // 初始化加载商品列表
    this.loadGoodsPageQuery();
  },
  methods: {
    ...mapMutations({
      setProduct: "user/SAVE_PRODUCT",
    }),
    onCardClick(val) {
      this.setProduct(val);
      // 这里进行数据的存储
      router.push({name: "ShopInfo"});
    },
    /**
     * 请求服务器商品数据
     */
    loadGoodsPageQuery() {
      this.query.categoryId = [0, 1, 2].includes(this.currentProductType)
          ? ""
          : this.currentProductType - 2;

      const queryData = {
        pageRequestDto: {
          page: this.currentPage,
          size: this.pageSize,
        },
        query: this.query,
      };
      productsPageQuery(queryData)
          .then((res) => {

            this.products = this.transformProductData(res.data.records);
            this.total = res.data.total;
            console.log(res);
          })
          .catch((err) => {
            console.log(err);
          })
          .finally(() => {
          });
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.loadGoodsPageQuery();
    },
    transformProductData(records) {
      return records.map(({
                            productId,
                            productName: title,
                            description: desc,
                            price,
                            stock,
                            createdTime,
                            storeId,
                            organizationId,
                            productImage: img,
                            storeName,
                            companyName,
                          }) => ({
        productId,
        title,
        desc,
        price,
        stock,
        createdTime,
        storeId,
        organizationId,
        img,
        storeName,
        companyName,
      }));
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.loadGoodsPageQuery();
    },
  },
};
</script>

<style scoped>
/* 商品区域整体样式 */
.product-section {
  max-width: 1200px;
  margin: 140px auto;
  padding: 20px;
  box-sizing: border-box;
}

/* 标题样式 */
.section-title {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
  font-weight: bold;
}

/* 商品行样式 */
.product-row {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start; /* 左对齐 */
}

/* 商品列样式 */
.product-col {
  margin-bottom: 20px;
}

/* 空块样式 */
.empty-col {
  margin-bottom: 20px;
}

.empty-block {
  height: 20px; /* 空块高度，可根据需要调整 */
  background-color: transparent; /* 空块背景色 */
}

/* 商品卡片样式 */
.product-card {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.product-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

/* 商品图片样式 */
.product-img {
  width: 100%;
  height: 200px;
  object-fit: cover;
  display: block;
}

/* 商品信息样式 */
.product-info {
  padding: 15px;
}

.product-title {
  font-size: 16px;
  margin-bottom: 8px;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.product-desc {
  font-size: 12px;
  color: #999;
  margin-bottom: 10px;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.product-price {
  font-size: 18px;
  color: #ff6700;
  margin-bottom: 15px;
  font-weight: bold;
}

.buy-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  color: #ff6700;
  font-size: 14px;
  transition: color 0.3s ease;
}

.buy-btn:hover {
  color: #ff8a00;
}

/* 响应式设计 */
@media (min-width: 992px) {
  .product-col {
    flex: 0 0 calc(25% - 20px); /* 大屏幕：每行4个商品 */
  }
}

@media (min-width: 768px) and (max-width: 991px) {
  .product-col {
    flex: 0 0 calc(33.333% - 20px); /* 中等屏幕：每行3个商品 */
  }
}

@media (max-width: 767px) {
  .product-col {
    flex: 0 0 calc(50% - 20px); /* 小屏幕：每行2个商品 */
  }

  .product-img {
    height: 150px;
  }

  .product-title {
    font-size: 14px;
  }

  .product-desc {
    font-size: 11px;
  }

  .product-price {
    font-size: 16px;
  }
}
</style>